package com.iteaj.iot.test.server.udp;

import com.iteaj.iot.event.IotEvent;
import com.iteaj.iot.server.ServerEventListener;
import com.iteaj.iot.server.SocketServerComponent;
import com.iteaj.iot.server.udp.UdpServerComponent;
import com.iteaj.iot.server.udp.impl.DefaultUdpServerMessage;
import com.iteaj.iot.server.udp.impl.DefaultUdpServerProtocol;
import com.iteaj.iot.server.udp.impl.DefaultUdpServerProtocolHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@ConditionalOnProperty(prefix = "iot.test", name = "udp.start", havingValue = "true")
public class DefaultUdpHandle implements DefaultUdpServerProtocolHandle, ServerEventListener {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object handle(DefaultUdpServerProtocol protocol) {
        DefaultUdpServerMessage requestMessage = protocol.requestMessage();
        String reqMsg = new String(requestMessage.getMessage());
        System.out.println("------------------------- 接收到UDP报文：" + reqMsg);

        // 把报文原封不动响应(响应此请求)
        protocol.response((reqMsg + ":resp").getBytes(StandardCharsets.UTF_8));

        // 主动向发送方发起一次请求
        DefaultUdpServerProtocol.write((reqMsg + ":req").getBytes(StandardCharsets.UTF_8), requestMessage.getSender());

        // 使用设备编号的方式发起一次请求
        DefaultUdpServerProtocol.write((reqMsg + ":req(deviceSn)").getBytes(StandardCharsets.UTF_8), protocol.getEquipCode());
        return null;
    }

    @Override
    public boolean isMatcher(IotEvent event) {
        return ServerEventListener.super.isMatcher(event)
                && event.getComponent() instanceof UdpServerComponent;
    }

    @Override
    public void online(String source, SocketServerComponent component) {
        logger.info("UDP客户端上线({}) 客户端编号：{}", component.getName(), source);
    }

    @Override
    public void offline(String source, SocketServerComponent component) {
        logger.info("UDP客户端掉线({}) 客户端编号：{}", component.getName(), source);
    }
}
